﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Reflection;
using System.ComponentModel;

using LongNet.Util;
using LongNet.Config;
using LongNet.Web;
using LongNet.Web.Email;
using LongNet.Log;
namespace LongNet.Web.Controllers
{

    public class LongNetAttribute : Attribute
    {
        public LongNetAttribute(string description)
        {
            Description = description;
        }
        public override string ToString()
        {
            return string.Format("{0}", Description);
        }
        public string Description { set; get; }     
    }

    public class Catalogs
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int SubId { get; set; }
    }
    [HandleError]
    public class HomeController : Controller
    {
        private static LongNet.Util.LogManager.Logger logger = LongNet.Util.LogManager.GetCurrentClassLogger();

        private string result = string.Empty;
        [LongNet("首页")]
        public ActionResult Index(string showView,string toAction)
        {
            //if (logger.IsDebugEnabled)
            //    logger.Debug("欢迎使用 ASP.NET MVC");
            //return RedirectToAction("Index", "EasyUI");
       

            //Response.ContentType = "text/html";
            //Response.Charset = "utf-8";                    
          
            //return Content(HttpUtil.HttpGet("http://www.baidu.com/"));

          //string user= ConfigService.LongNetConfig.Author;       
          //ConfigService.EditLongNetConfig("long.peng", 1.1);        

            //Serializer.ConvertToXmlFile(new RetJson("12", "You are Welcome", "{444}"),string.Format(@"d:\{0}.config",typeof(RetJson).Name));
            //var rt=Serializer.ConvertFromXmlFile<RetJson>(string.Format(@"d:\{0}.config",typeof(RetJson).Name));
            if (!string.IsNullOrEmpty(showView))
                return View(showView);
            if (!string.IsNullOrEmpty(toAction))
                return RedirectToAction(toAction);
            //输出组织结构
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            Assembly assembly = Assembly.GetExecutingAssembly(); //this.GetType().Assembly;
            var types= assembly.GetTypes();
            foreach (var t in types)
            {
                if (t.Name.IndexOf("Controller") != -1)
                {
                    sb.AppendLine(t.Name + "<br/>");
                    var methods = t.GetMethods();
                    //var members = t.GetMembers();
                    foreach (var me in methods)
                    {
                        if ((me.ReturnType == (typeof(ActionResult)) || (me.ReturnType == typeof(ContentResult)) || (me.ReturnType == typeof(JsonResult))))
                        {                            
                            sb.AppendLine(string.Format("<a href=\"/{0}/{1}\">{2}</a>", t.Name.Replace("Controller", ""), me.Name, me.Name));
                            foreach (var attr in me.GetCustomAttributes(typeof(LongNetAttribute),false))
                            {
                                sb.AppendLine(attr.ToString());
                                //sb.Append("<span style=\"width:3px;\">.</span>");
                            }
                        }                       
                    }
                    sb.AppendLine("<br/>");
                }
               
            }
            ViewData["navigation"] = sb.ToString();
            return View();
           //return Content();
        }

        [LongNet("邮件系统")]
        public ActionResult Email()
        {

            EmailSender email = new EmailSender(); 
           
            Message message = new Message();
           // message.From = "googlemao@163.com";
           // message.To = "googlemao@163.com";
           // message.UserName = "googlemao";
           // message.Password = "";
           // message.Server = "smtp.163.com ";
           // message.Subject = "测试html";
           // //email.Attachment = new System.Net.Mail.Attachment(@"D:\beautiful.jpg");
           // message.Content = "感谢您收看，测试成功~";
           //// email.SendMail("感谢您收看，测试成功~");           
           // //message.Body = "asas";
           //Serializer.ConvertToXmlFile(message, string.Format(@"d:\{0}.config", typeof(Message).Name));
            
            var msg = Serializer.ConvertFromXmlFile<Message>(string.Format(@"d:\{0}.config", typeof(Message).Name));

            if (PublicClass.CopyProperties(msg, email))
            {
                // LongNet.Util.StringUtil.
                email.Content = CommonClass.DecryptFromBase64String(email.Content);
                email.SendMail(null);
            }
            //Serializer.ConvertToXmlFile(message, string.Format(@"d:\{0}.config", typeof(Message).Name));
            return Content("Email");
          
        }
         [LongNet("收邮件")]
        public ActionResult Pop3()
        {
            string result = "";
            try
            {
                LongNet.Web.Email.Pop3.Pop3Client client = new Email.Pop3.Pop3Client();
                client.Connect("googlemao", "", "pop.163.com.", 110);
                List<LongNet.Web.Email.Pop3.Message> list= client.GetMessageList();
                if (list != null)
                {
                    LongNet.Web.Email.Pop3.Message msg=client.GetMessage(list[0]);
                    result += msg.Content + msg.Body;
                    //foreach (var l in list)
                    //{
                    //   // logger.Debug(l.Content);
                    //    result += l.ToString();
                    //}
                }
                else
                {
                    logger.Error("no email");
                }
                client.Disconnect();             
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }


            return Content(result);
        }
         [LongNet("base64字符串加密解密")]
        public ActionResult base64(int type,string input)
        {
            string result = string.Empty;
            if (type == 1)
            {
                result = CommonClass.EncryptToBase64String(input);
            }
            else
            {
                result = CommonClass.DecryptFromBase64String(input);
            }
            return Content(result);
        }
        public ActionResult verifyimage()
        {
            
            string code;
            byte[] s = VerifyImage.GenerateImage(VerifyImage.GenerateOptions.Background,out code);
            return File(s, LongNet.Util.Utils.GetContentType(".jpg"));          
        }

        public ActionResult Music()
        {
            return View();
        }
        public ActionResult HttpGetImage()
        {
            HttpUtil.HttpGetImage("http://www.yangtse.com/sytj/ktmt/200907/W020090730371501094983.jpg", null);
            return Content("HttpGetImage");
        }

        public ActionResult DeepDownLoadLink(string url)
        {
            HttpDownLoad down = new HttpDownLoad("");
            down.DownComplated += new HttpDownLoad.DownComplatedEventHandler(down_DownComplated);
            down.DeepDownLinkImage(HttpUtility.UrlDecode(url));         
            return Content("DeepDownLoadLink");
        }
       
        void down_DownComplated(object sender, DownComplatedEventArgs e)
        {
            logger.Debug("down_DownComplated");
            //throw new NotImplementedException();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult ImageZoom()
        {
            //return RedirectToAction("Index", "Web1");
            return View();
        }
         public ActionResult TestHttpGet()
        {
            //return RedirectToAction("Index", "Web1");          
            HttpDownLoad down = new HttpDownLoad("www.kundao888.com.cn");
            down.DownComplated += new HttpDownLoad.DownComplatedEventHandler(down_DownComplated);
            down.DeepDownLinkImage("http://www.kundao888.com.cn/athena/contact/tjy92.html");      
            return Content("TestHttpGet");
        }

         public ActionResult DataBind()
         {
             ContentResult cr = new ContentResult();
             IList<Catalogs> catalist = new List<Catalogs>();
             catalist.Add(new Catalogs { ID = 1, Name = "first1", SubId = 11 });
             catalist.Add(new Catalogs { ID = 2, Name = "first2", SubId = 11 });
             catalist.Add(new Catalogs { ID = 3, Name = "first3", SubId = 11 });
             catalist.Add(new Catalogs { ID = 4, Name = "first4", SubId = 11 });
             cr.ContentType = "application/json; charset=utf-8";
             string json = "{\"data\":[";
             foreach (var cat in catalist)
             {
                 json += "{";
                 json += string.Format("\"ID\":\"{0}\",\"Name\":\"{1}\",\"SubId\":\"{2}\"",cat.ID,cat.Name,cat.SubId);
                 json += "},";
             }
             json.TrimEnd(',');
             json += "]}";
             cr.Content = json;
             //cr.Content = "{\"error_code\":\"104\",\"error_message\":\"122\",\"data\":\"122\"}";
             return cr;
         }
        public JsonResult JsonAjax()
        {
            // return Json("{\"error_code\":\"104\",\"error_message\":\"122\",\"data\":\"122\"}");
            return Json(new RetJson(true,"12", "You are Welcome", "{}"));
        }

        public ActionResult Active()
        {
           Result rs= Bussiness.pcl.ActivityGoodsB.Add(new Model.pcl.ActivityGoods { Id = 12, ActionId = "11", MailTitle = "11" });
            //if(rs.me
            return View();
        }

        public ActionResult Index1(string text = "")
        {            
            string result = "";
            text = HttpUtility.HtmlDecode(text);
            string[] regPattern = { @"^(\-|\+)?\d+(\.\d+)?$"/*正负0*/,@"^[0-9]*$"/*只能数字*/,@"^\d{4}$"/*只能4位数字*/,@"^\d{4,}$"/*至少4位数字*/ 
                  ,@"^\d{2,4}$"/*2~4位数字*/ ,@"^\+?[1-9][0-9]*$"/*非0正整数*/ ,@"^.{3}$"/*长度为3的字符串*/ ,@"^[A-Za-z]+$"/*26个英文字母*/     
                  ,@"^[A-Z]+$"/*26个大写英文字母*/,@"^[a-z]+$"/*26个小写英文字母*/,@"^[A-Za-z0-9]+$"/*26个英文字母与数字*/,@"^\w+$"/*1个或多个数字字母下划线*/   
                  ,@"^[A-Za-z]\w{5,17}$"/*字母开始，由数字字母下划线组成的6到18位*/
                  ,@"[^%&';=?$]+"/*是否包含^%&';=?$等特殊字符串*/,@"^[\u4e00-\u9fa5]{0,}$"/*只能输入汉字*/
                  ,@"^\w+([-+.]\w+)*@\w+([-+.]\w+)*\.\w+([-+.]\w+)*$"/*email验证*/  ,@"^\w+(love)+pcl$"/*字母数字下划线开始 包含1个或多个love然后pcl结束*/
                ,@"^((\d{3,4}-)?\d{7,8}$)|(\d{11})$"/*电话号码格式*/
                ,@"^\d{15}|d{18}$"/*身份证号码*/,@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"/*IP*/,@"[^abc]"/*求反，abc以为的*/
                  ,"a.c"/*.匹配除\n换行符之外的单个字符,[\s\S]匹配所有单子字符，匹配abc，acc */
                  ,@"^<.*>.*<\/\1>|<.*\/>$"/*html格式*/,@"^[1]+[3,5]+\d{9}$"/*tel*/,@"^1[3,5]{1}\d{9}$"/*最标准的tel，测试*/ //13683864187
                                  };
            /*正则以@"^"形式，\加字符表示转义，如\d数字,\+\-实际+-符号,\.实际小数点, .代表任意字符,$结束符 ,(reg)?表示0个或1个匹配,+表示1个或多个,*表示0个或多个，如([+-.]\w+)*,[a-z]表示从a到z连续值之一,\w数字字母下划线
             @"^"开头表示从第一个开始匹配,如果不是^开头表示包含.如@"\d{4}$"包含4个数字结束；\s   表示空格。\n换行,\b字符边界,\B非边界，\D非数字，\W非字母数字下划线，[^\x00-\xff]双字节字符。
             */
            //<a   href= "aUrl "> something </a>  @"<a\s*href=\s*"[^<>]">\s*"
            int count = 0;
            foreach (var reg in regPattern)
            {
                result += reg + ":" + Regex.IsMatch(text, reg).ToString() + "\r\n";
                count += 1;
                if (count % 12 == 0)
                {
                    count = 0;
                    result += "<br />";
                }
            }

            //http://space.cnblogs.com/q/**/   //@"^http://space.cnblogs.com/q/\.*$"/
            return Content(result);
            //return View();
        }

        /// <summary>
        /// 2011-05-13 14:38
        /// </summary>
        /// <returns></returns>
        [LongNet("IEnumerable,枚举")]
        public ActionResult Collections()
        {
            // Testing Tokens by breaking the string into tokens:
            Tokens f = new Tokens("This is a well-done program.",
               new char[] { ' ', '-' });
            foreach (string item in f)
            {
                result += item + "<br/>";
            }
            return Content(result);
        }

        [LongNet("跳转视图")]
        public ActionResult GoToView([DefaultValue("css")]string viewName)
        {
            if (!viewName.IsNullOrEmpty())
            {
                return View(viewName);
            }
            return View("Index");
        }
    
    }

    // Declare the Tokens class:
    public class Tokens : IEnumerable
    {
        private string[] elements;

        public  Tokens(string source, char[] delimiters)
        {
            // Parse the string into tokens:
            elements = source.Split(delimiters);
        }

        // IEnumerable Interface Implementation:
        //   Declaration of the GetEnumerator() method 
        //   required by IEnumerable
        public IEnumerator GetEnumerator()
        {
            return new TokenEnumerator(this);
        }

        // Inner class implements IEnumerator interface:
        private class TokenEnumerator : IEnumerator
        {
            private int position = -1;
            private Tokens t;

            public TokenEnumerator(Tokens t)
            {
                this.t = t;
            }

            // Declare the MoveNext method required by IEnumerator:
            public bool MoveNext()
            {
                if (position < t.elements.Length - 1)
                {
                    position++;
                    return true;
                }
                else
                {
                    return false;
                }
            }

            // Declare the Reset method required by IEnumerator:
            public void Reset()
            {
                position = -1;
            }

            // Declare the Current property required by IEnumerator:
            public object Current
            {
                get
                {
                    return t.elements[position];
                }
            }
        }       
    }

    [Serializable]
    public class RetJson
    {
        public RetJson(bool _success, string _error_code, string _error_message, string _data)
        {
            success = _success;
            error_code = _error_code;
            error_message = _error_message;
            data = _data;
        }

        public RetJson()
        {          
        }
        public bool success { get; set; }
        public string error_code { get; set; }
        public string error_message { get; set; }
        public string data { get; set; }
    }
}
